package com.qingfeng.core.config.database;

import org.apache.ibatis.session.SqlSessionFactory;
import org.aspectj.apache.bcel.util.ClassLoaderRepository;
import org.aspectj.apache.bcel.util.ClassLoaderRepository.SoftHashMap;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @description: 集成MyBatis
 * @author:LWY
 * @date: 2017/10/12 16:10
 * @modified:
 */
@Configuration
@AutoConfigureAfter({DataSourceConfiguration.class})
public class MybatisConfiguration extends MybatisAutoConfiguration {

    /**
     * 主数据库源
     */
    @Resource(name = "masterDataSource")
    private DataSource masterDataSource;

    /**
     * 从数据库源
     */
    @Resource(name = "slaveDataSource")
    private DataSource slaveDataSource;

    /**
     * @return mybatis 数据库会话工厂
     * @throws Exception
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        return super.sqlSessionFactory(roundRobinDataSouceProxy());
    }

    /**
     * @return 动态获取的数据库源
     */
    public AbstractRoutingDataSource roundRobinDataSouceProxy() {
        ReadWriteSplitRoutingDataSource proxy = new ReadWriteSplitRoutingDataSource();
        SoftHashMap targetDataResources = new ClassLoaderRepository.SoftHashMap();
        targetDataResources.put(DataBaseContextHolder.DataBaseType.MASTER, masterDataSource);
        targetDataResources.put(DataBaseContextHolder.DataBaseType.SLAVE, slaveDataSource);
        proxy.setDefaultTargetDataSource(masterDataSource);//默认源
        proxy.setTargetDataSources(targetDataResources);
        return proxy;
    }

}
